<script setup lang="ts">

import { onMounted, reactive, ref } from 'vue'
import { downloadCode, tableList, tableRemove } from '@/api/system/generator/table'
import type { GeneratorTable, GeneratorTemplate } from '@/api/system/generator/generator'
import type { PageInfo, Result } from '@/tools/request'
import { type FormInstance, Message, Modal } from '@arco-design/web-vue'
import { templateList } from '@/api/system/generator/template'
import router from '@/router'

const table = reactive({
  rowSelection: {
    showCheckedAll: true,
    onlyCurrent: false
  },
  queryForm: {} as GeneratorTable,

  pageInfo: {} as PageInfo<GeneratorTable>,
  getTableList: (current: number) => {
    tableList(table.queryForm, {
      pageNum: current,
      pageSize: table.pageInfo.pageSize
      //@ts-ignore
    }).then((resp: Result<PageInfo<GeneratorTable>>) => {
      table.pageInfo = resp.data
    })
  },
  tableRemove: (record: GeneratorTable) => {
    Modal.confirm({
      title: '警告!',
      content: `确定删除 【${record.commentName}】 数据吗？`,
      onOk() {
        tableRemove(record.id).then(() => {
          Message.success('删除成功')
          table.getTableList()
        })
      }
    })
  }
})

const generator = reactive({
  visible: false,
  checkBtn: 'view',
  template: {} as GeneratorTemplate,
  templateList: [] as GeneratorTemplate[],
  form: {
    tableId: null,
    templateId: null
  } as any,
  open: (record: GeneratorTable) => {
    generator.visible = true
    generator.form.tableId = record.id
  },
  //触发提交
  triggerSubmit: (ele: HTMLElement, model: string) => {
    generator.checkBtn = model
    ele.click()
  },
  //生成按钮时间
  submit: ({ values, errors }: any) => {
    if (errors) {
      return
    }
    if (generator.checkBtn == 'view') {
      //跳转预览页面
      router.push({ path: '/generator/template/view', query: generator.form })
      return
    }
    //TODO 触发下载
    downloadCode(generator.form)
  },
  loadGeneratorTemplate: () => {
    //@ts-ignore
    templateList({}, { pageSize: 999999999, pageNum: 1 }).then((resp: Result<PageInfo<GeneratorTemplate>>) => {
      generator.templateList = resp.data.list
    })
  },
  //更改模板时
  changeTemplate: (value: number) => {
    generator.template = generator.templateList[value]
    generator.form.templateId = generator.template.id
  }
})

onMounted(() => {
  table.getTableList()
  generator.loadGeneratorTemplate()
})
</script>

<template>

  <a-breadcrumb class="my-3">
    <a-breadcrumb-item>系统工具</a-breadcrumb-item>
    <a-breadcrumb-item>代码生成</a-breadcrumb-item>
  </a-breadcrumb>
  <a-layout-content>
    <a-card>
      <template #title>
        代码生成
      </template>
      <a-form :model="table.queryForm" ref="searchFormRef" @submit="table.getTableList" label-align="left"
              v-permission="'permission:generator:table:list'">
        <a-row :gutter="15" style="height: 32px">
          <a-col :span="6">
            <a-form-item field="tableName" label="表名">
              <a-input v-model="table.queryForm.tableName"></a-input>
            </a-form-item>
          </a-col>
          <a-col :span="6">
            <a-form-item field="commentName" label="表备注">
              <a-input v-model="table.queryForm.commentName"></a-input>
            </a-form-item>
          </a-col>
          <a-divider direction="vertical" :margin="20" style="height: 32px"></a-divider>
          <a-col :span="6">
            <a-space>
              <a-button type="primary" html-type="submit">
                <template #icon>
                  <IconSearch />
                </template>
                搜索
              </a-button>
              <a-button type="secondary" @click="$refs.searchFormRef.resetFields()">
                <template #icon>
                  <IconRefresh />
                </template>
                重置
              </a-button>
            </a-space>
          </a-col>
        </a-row>
      </a-form>

      <a-divider :margin="16"></a-divider>
      <RouterLink to="/generator/form" v-permission="'permission:generator:table:create'">
        <a-button type="primary" class="mb-3">
          <template #icon>
            <IconPlus />
          </template>
          新建
        </a-button>
      </RouterLink>

      <a-table row-key="id" :row-selection="table.rowSelection" :data="table.pageInfo.list" :pagination="false">
        <template #columns>
          <a-table-column data-index="id" title="ID" align="center" width="80" />
          <a-table-column data-index="commentName" title="表备注名称" />
          <a-table-column data-index="tableName" title="表名称" />
          <a-table-column data-index="structName" title="结构体名称" />
          <a-table-column data-index="createTime" title="创建时间" />
          <a-table-column title="操作" width="240">
            <template #cell="{record}">
              <a-space>
                <a-button @click="generator.open(record)" type="text"
                          v-permission="'permission:generator:table:preview'">
                  <template #icon>
                    <IconSettings />
                  </template>
                  生成
                </a-button>
                <RouterLink :to="{path: '/generator/form',query:{id: record.id}}"
                            v-permission="'permission:generator:table:update'">
                  <a-button type="text">
                    <template #icon>
                      <IconEdit />
                    </template>
                    修改
                  </a-button>
                </RouterLink>
                <a-button type="text" @click="table.tableRemove(record)" class="text-danger"
                          v-permission="'permission:generator:table:delete'">
                  <template #icon>
                    <IconDelete />
                  </template>
                  删除
                </a-button>
              </a-space>
            </template>
          </a-table-column>
        </template>
      </a-table>
      <div class="d-flex justify-content-end mt-2">
        <a-pagination :total="table.pageInfo.total" :page-size="table.pageInfo.pageSize"
                      :current="table.pageInfo.pageNum"
                      @change="table.getTableList" class="mt-3"></a-pagination>
      </div>
    </a-card>

  </a-layout-content>

  <a-modal v-model:visible="generator.visible" title="生成代码配置" title-align="start">
    <a-form :model="generator.form" @submit="generator.submit">
      <a-form-item label="生成模板" field="templateId"
                   :rules="[{required: true,message:'请选择模板'}]"
                   validate-trigger="blur"
                   hide-asterisk
      >
        <a-select @change="generator.changeTemplate">
          <a-option :label="v.title" :value="i" :key="i" v-for="(v,i) in generator.templateList"></a-option>
        </a-select>
      </a-form-item>
      <a-form-item label="创建者">
        <a-input v-model="generator.template.createBy" disabled />
      </a-form-item>
      <a-form-item label="创建时间">
        <a-input v-model="generator.template.createTime" disabled />
      </a-form-item>
      <a-form-item label="更新时间">
        <a-input v-model="generator.template.updateTime" disabled />
      </a-form-item>
      <button type="submit" style="display: none" ref="submitRef"></button>
    </a-form>

    <template #footer>
      <div class="w-100 justify-content-center text-center">

        <a-space>
          <a-button @click="generator.triggerSubmit($refs.submitRef,'view')">
            <template #icon>
              <IconEye />
            </template>
            预览
          </a-button>
          <a-button @click="generator.triggerSubmit($refs.submitRef,'download')" type="primary">
            <template #icon>
              <IconDownload />
            </template>
            下载
          </a-button>
        </a-space>
      </div>
    </template>
  </a-modal>
</template>

<style scoped lang="scss">

</style>
